package com.starblink.comment.ui

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Rect
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.*
import androidx.appcompat.app.AppCompatDialog
import com.starblink.android.basic.appsflyer.AppsflyerManager
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.basic.util.CommUtils.getColor
import com.starblink.basic.util.KeyboardUtils
import com.starblink.comment.R
import com.starblink.rocketreserver.AddPostCommentMutation
import com.starblink.rocketreserver.fragment.PostCommentF
import com.starblink.rocketreserver.type.PostCommentAddRequest
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import java.util.*
import kotlin.concurrent.schedule

/**
 * 内容评论框
 */
class PostCommentDialog(private val mContext: Activity, theme: Int) :
    AppCompatDialog(mContext, theme) {
    private var imm: InputMethodManager? = null
    private var etInput: EditText? = null
    private var tvPost: TextView? = null
    private var rlDlg: RelativeLayout? = null
    private var mLastDiff = 0
    private var tvNumber: TextView? = null
    private var maxNumber = 500

    lateinit var postId: String
    lateinit var postContentType: String

    var replyCommentId: String = "0"//回复父评论

    private lateinit var listener: (PostCommentF) -> Unit

    fun setTextSendListener(listener: (PostCommentF) -> Unit) {
        this.listener = listener
    }

    /**
     * 最大输入字数  默认200
     */
    @SuppressLint("SetTextI18n")
    fun setMaxNumber(maxNumber: Int) {
        this.maxNumber = maxNumber
        tvNumber!!.text = "0/$maxNumber"
    }

    /**
     * 设置输入提示文字
     */
    fun setHint(text: String?) {
        etInput!!.hint = text
    }

    /**
     * 设置内容id
     */
    fun setId(id: String) {
        postId = id
    }

    /**
     * 设置内容Type
     */
    fun setContentType(contentType: String) {
        postContentType = contentType
    }

    /**
     * 设置回复用户id
     */
    fun setReplyId(id: String) {
        replyCommentId = id
    }

    private fun init() {
        setContentView(R.layout.dialog_post_comment)
        etInput = findViewById<View>(R.id.et_input_message) as EditText?
        tvNumber = findViewById<View>(R.id.tv_test) as TextView?
        etInput!!.requestFocus()

        Timer().schedule(300) {
            KeyboardUtils.showSoftkeyboard(mContext)
        }

        val rldlgview = findViewById<View>(R.id.rl_inputdlg_view) as LinearLayout?
        etInput!!.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
            override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
            override fun afterTextChanged(editable: Editable) {
                tvNumber!!.text = editable.length.toString() + "/" + maxNumber
                if (editable.length > maxNumber) {
                    /*dot_hong颜色值：#E73111,text_bottom_comment颜色值：#9B9B9B*/
                    tvNumber!!.setTextColor(getColor(com.starblink.basic.style.R.color.sk_red400))
                } else {
                    tvNumber!!.setTextColor(getColor(com.starblink.basic.style.R.color.sk_gray400))
                }
                if (editable.isEmpty()) {
                    tvPost!!.setBackgroundResource(R.drawable.btn_send_normal)
                } else {
                    tvPost!!.setBackgroundResource(R.drawable.btn_send_pressed)
                }
            }
        })
        tvPost = findViewById<View>(R.id.confrim_btn) as TextView?
        imm = mContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        tvPost!!.setOnClickListener(View.OnClickListener {
            val msg = etInput!!.text.toString().trim { it <= ' ' }
            if (msg.length > maxNumber) {
                Toast.makeText(mContext, "Text exceeds limit", Toast.LENGTH_LONG).show();
                return@OnClickListener
            }
            if (!TextUtils.isEmpty(msg)) {
                postComment(msg)
            } else {
                //                    Toast.makeText(mContext, "请输入文字", Toast.LENGTH_LONG).show();
            }
            etInput!!.text = null
        })
        etInput!!.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
            when (actionId) {
                KeyEvent.KEYCODE_ENDCALL, KeyEvent.KEYCODE_ENTER -> {
                    if (etInput!!.text.length > maxNumber) {
                        Toast.makeText(mContext, "Text exceeds limit", Toast.LENGTH_LONG).show()
                        return@OnEditorActionListener true
                    }
                    if (etInput!!.text.isNotEmpty()) {
                        imm!!.hideSoftInputFromWindow(etInput!!.windowToken, 0)
                        dismiss()
                    } else {
//                        Toast.makeText(mContext, "请输入文字", Toast.LENGTH_LONG).show()
                    }
                    true
                }

                KeyEvent.KEYCODE_BACK -> {
                    dismiss()
                    false
                }

                else -> false
            }
        })
//        etInput!!.setOnKeyListener { view, i, keyEvent -> false }
        rlDlg = findViewById(R.id.rl_outside_view)
        rlDlg!!.click { v -> if (v.id != R.id.rl_inputdlg_view) dismiss() }
        rldlgview!!.addOnLayoutChangeListener { view, i, i1, i2, i3, i4, i5, i6, i7 ->
            val r = Rect()
            //获取当前界面可视部分
            window!!.decorView.getWindowVisibleDisplayFrame(r)
            //获取屏幕的高度
            val screenHeight = window!!.decorView.rootView.height
            //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
            val heightDifference = screenHeight - r.bottom
            if (heightDifference <= 0 && mLastDiff > 0) {
                dismiss()
            }
            mLastDiff = heightDifference
        }
        rldlgview.click {
            imm!!.hideSoftInputFromWindow(etInput!!.windowToken, 0)
            dismiss()
        }
        setOnKeyListener { dialogInterface, keyCode, keyEvent ->
            if (keyCode == KeyEvent.KEYCODE_BACK && keyEvent.repeatCount == 0) dismiss()
            false
        }
    }

    private fun postComment(msg: String) {
        CoroutineScope(Dispatchers.IO).launch {
            val response = SkGqlClient.skMutation(
                AddPostCommentMutation(
                    postCommentAdd = PostCommentAddRequest(
                        postId = postId,
                        replyCommentId = replyCommentId,
                        content = msg
                    )
                ),
                showDefaultLoading = true
            )
            MainScope().launch {
                if (response?.data != null && response.data!!.addPostComment != null && response.data!!.addPostComment.postCommentF != null) {
//                    toast("Successfully comment")
                    // 埋点
                    AppsflyerManager.reportContentComment(
                        mapOf(
                            "af_content_id" to postId,
                            "af_content_type" to postContentType
                        ),
                    )
                    if (listener != null) {
                        listener.invoke(
                            response.data!!.addPostComment.postCommentF
                        )
                    }
                    imm!!.showSoftInput(etInput, InputMethodManager.SHOW_FORCED)
                    imm!!.hideSoftInputFromWindow(etInput!!.windowToken, 0)
                    etInput!!.setText("")
                    dismiss()
                }
            }
        }

    }

    private fun setLayout() {
        window!!.setGravity(Gravity.BOTTOM)
        val m = window!!.windowManager
        val d = m.defaultDisplay
        val p = window!!.attributes
        p.width = WindowManager.LayoutParams.MATCH_PARENT
        p.height = WindowManager.LayoutParams.WRAP_CONTENT
        window!!.attributes = p
        setCancelable(true)
        window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
    }

    override fun dismiss() {
        super.dismiss()
        //dismiss之前重置mLastDiff值避免下次无法打开
        mLastDiff = 0
    }

    override fun show() {
        super.show()
    }

    init {
        this.window!!.setWindowAnimations(com.starblink.android.basic.R.style.main_menu_animstyle)
        init()
        setLayout()
    }
}